<?php
/**
 * This file is part of Hyperf Mall.
 *
 * @link     https://gitee.com/scwlkj/hypref_mall
 * contact  hyperf_mall@163.com
 */
namespace App\Repository;

use App\Cache\AddressCache;
use App\Model\AddressModel;
use App\Model\BaseModel;
use App\Service\Config\AreaService;
use Hyperf\Database\Model\Model;
use Hyperf\Di\Annotation\Inject;

class AddressRepository extends BaseRepository
{
    /**
     * @Inject
     * @var AddressModel
     */
    protected $model;

    /**
     * @Inject
     * @var AreaService
     */
    protected AreaService $areaService;

    /**
     * Notes:
     * Author:Jurij.cao
     * Date:2022/7/1
     * @param $member_id
     * @return array|null
     */
    public function getAddressListByMemberId($member_id): ?array
    {
        return AddressCache::getInstance()->get($member_id);
    }

    /**
     * Notes: 获取详细地址
     * @param int $member_id
     * @param int $id 为0获取默认地址
     * @return array|null
     */
    public function getAddress(int $member_id, int $id = 0): ?array
    {
        return AddressCache::getInstance()->getAddress($member_id, $id);
    }

    /**
     * Notes: pc端添加收货地址
     * Author: Bruce.z
     * DateTime: 2022/10/18 10:48
     * @param int $member_id
     * @param array $param
     * @return BaseModel|Model
     */
    public function createByPc(int $member_id, array $param)
    {
        $area_ids = explode(",", $param['regions']);
        $_data = [
            'member_id'=>$member_id,
            'ship_addr'=>$param['detailAddress'],
            'ship_name'=>$param['name'],
            'ship_mobile'=>$param['mobile'],
            'is_default'=>intval($param['isDefault']),
            'ship_province_id'=>$area_ids[0]??0,
            'ship_city_id'=>$area_ids[1]??0,
            'ship_county_id'=>$area_ids[2]??0,
        ];

        if($param['id']??0){
            $re = $this->updateByConditions(['id'=>$param['id']], $_data);
        }else{
            $re = $this->model->baseAdd($_data);
        }
        if($_data['is_default'] == 1){
            $_id =  $re['id'] ?? $param['id'];
            $this->updateByConditions(['member_id'=>$member_id,['id','!=',$_id]],['is_default'=>0]);
        }

        return $re;
    }

    public function getRows(array $conditions = [], array $fields = ['*']): array
    {
        $data =  parent::getRows($conditions, $fields);

        foreach ($data as &$row){
            $row['address_name'] = $this->areaService->address($row['ship_county_id']);
        }
        return $data;
    }

    /**
     * Notes: 设置默认地址
     * Author: Bruce.z
     * DateTime: 2022/10/19 10:28
     * @param int $member_id
     * @param int $id
     * @return bool
     */
    public function setDefault(int $member_id, int $id): bool
    {
        $this->updateByConditions(['member_id'=>$member_id,['id','!=',$id]],['is_default'=>0]);
        $this->updateByConditions(['member_id'=>$member_id,'id'=>$id],['is_default'=>1]);

        return true;
    }
}
